/**
 * Created by wangguoqing on 2017/12/21.
 */
var params = new Object();
var oldRolesByOrgMap = new Map();
var setRolesDataArray = null;

var url = path + "/system/user/listOrgRole";
$(function () {
    setValue();
    //初始化已分配的组织机构
    initOrgRoles();

    var grid = $("#tt");
    initGrid(grid);
    //设置datagrid样式
    grid.datagrid({
        fit: false
    });
    grid.datagrid("resize", {
        height: 300
    })
});

//获取父页面的值
function setValue() {
    var rows = parent.$('#tt').datagrid('getSelections');
    var rowData = rows[0];
    $("#userId").val(rowData.userId);
    $("#userCode").val(rowData.userCode);
    $("#userName").val(rowData.userName);
    $("#phoneNo").val(rowData.phoneNo);
    $("#email").val(rowData.email);
    //重新渲染页面
    $.parser.parse();
}
//初始化已分配的组织机构 包含全部不分页，主要为存储 oldRolesByOrgArray
function initOrgRoles() {
    var initParam = new Object();
    initParam.type = 'update';
    initParam.userId = $("#userId").val();
    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: initParam,
        success: function callback(data) {
            var analyMsg = data;
            if (analyMsg.code != '0000') {
                $.messager.alert('操作提示', analyMsg.msg, 'info', function () {
                });
            } else {
                //returnDate 中设置roleDtos
                var returnDate = analyMsg.returnObject;
                var rows = returnDate.rows;
                $.each(rows, function (i, v) {
                    var roleParam = new Object();

                    //设置成json形式
                    var roleDtos = v.roleDtos;
                    roleParam.id = v.orgCode;
                    roleParam.orgName = v.orgName;
                    roleParam.orgCode = v.orgCode;
                    if (!String.isNull(v.userId)) {
                        roleParam.userId = v.userId;
                    } else {
                        roleParam.userId = "";
                    }

                    var strIds = "";
                    var setRolesArray = new Array();    //设置的角色名称数组
                    $.each(roleDtos, function (j, value) {
                        var roleNameParams = new Object();
                        roleNameParams.roleName = value.roleName;
                        roleNameParams.roleId = value.roleId;
                        if (j == 0) {
                            strIds += value.roleId;
                        } else {
                            strIds += "," + value.roleId;
                        }

                        setRolesArray.push(roleNameParams);
                        // console.log(JSON.stringify(roleNameParams));
                    });
                    roleParam.roleIds = strIds;
                    roleParam.roleDtos = JSON.stringify(setRolesArray);
                    oldRolesByOrgMap.put(v.orgCode, roleParam);
                });
            }
        },
        error: function (data, textstatus) {
            $.messager.alert('操作提示', data.responseText, 'error', function () {
            });
        }
    });
}

//初始化表格和数据
function initGrid(grid) {
    var columns = [
        {
            field: "id", title: "ID", hidden: true,
            align: "left", sortable: false, resizable: true, width: 120
        },
        {
            field: "orgName",
            title: "组织结构名称",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 240
        },
        {
            field: "orgCode",
            title: "组织结构编码",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 135
        },
        {
            field: "roleDtos",
            title: "已分配角色权限 ",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 400,
            formatter: function (value, row, index) {
                var js = "";
                $.each(row.roleDtos, function (index, val) {
                    if (index == 0) {
                        js += val.roleName;
                    } else {
                        js += "," + val.roleName;
                    }
                });
                return js;
            }
        }
    ];
    params.userId = $("#userId").val();
    params.type = 'update';
    initGridWithCheckBox(grid, params, url, columns, "#tb", "id");
    var options = $("#tt").datagrid("options");
    options.onLoadSuccess = function (data) {
        $('#tt').datagrid("fixRownumber");
    };

    grid.datagrid({
        title: '组织机构角色信息'
    })
    //getData(grid, params, url);
}

//修改增加的数据
function submit_update() {

    if (!validform("user_form")) {
        return;
    }
    var finalParams = new Object();
    finalParams.userId = $("#userId").val();
    finalParams.userCode =  $("#userCode").val();
    finalParams.userName =  $("#userName").val();
    finalParams.phoneNo =  $("#phoneNo").val();
    finalParams.email =  $("#email").val();

    var rowsAll = $('#tt').datagrid('getData');
    var rowsData = JSON.stringify(rowsAll.rows);
    finalParams.orgRoleList = rowsData;
    // console.log(JSON.stringify(finalParams));
    $.ajax({
        type: "POST",
        url: path+'/system/user/update',
        data: finalParams,
        dataType: "json",
       // contentType: "application/json",
        success: function callback(data) {
            var analyMsg = data;
            if (analyMsg.code != '0000') {
                $.messager.alert('操作提示', analyMsg.msg, 'error', function () {
                });
            } else {
                $.messager.alert("操作提示", "修改用户信息成功。", "info", function () {
                    parent.btnQuery();
                    closeLayer();
                });
            }
        },
        error: function (data, textstatus) {
            $.messager.alert('操作提示', data.responseText, 'info', function () {
            });
        }
    });

}

/**
 * 修改
 * */
function btnEditNodeByGrid() {
    var rows = $('#tt').datagrid('getSelections');
    if (rows.length == 0) {
        $.messager.alert("操作提示", "请选一个记录！", "info");
        return;
    } else if (rows.length == 1) {
        setGlobalVariable("role", JSON.stringify(rows));
        top.layer.open({
            type: 2,
            title: ['机构权限分配 - 修改','background: #38acff;'],
            shadeClose: true,
            shade: 0.3,
            area: ['710px', '500px'],
            content: path+'/system/user/orgRoleAllot' //iframe的url
            , end: function () {
                //需要对角色值更改
                var roles = rows[0].roleDtos;
                var setRolesData = getGlobalVariable("setOrgRoles");
                if (setRolesData.isJSON()) {
                    setRolesDataArray = JSON.parse(setRolesData)[0];
                    //map修改
                    oldRolesByOrgMap.put(setRolesDataArray.orgCode, setRolesDataArray);
                } else {
                    setRolesDataArray = [];
                }

                //先清空 datagrid中含有的数据
                $("#tt").datagrid("loadData", {total: 0, rows: []});
                //再添加datagrid数据
                //拼接rows内json
                var html = new Array();
                html.push('[');
                $.each(oldRolesByOrgMap.elements, function (i, v) {
                    if (i == 0) {
                        html.push('{');
                    } else {
                        html.push(',{');
                    }
                    $.each(v.value, function (index, val) {
                        if ("roleDtos" == index) {
                            html.push('"' + index + '" : ' + val + ',');
                        } else {
                            html.push('"' + index + '" : ' + '"' + val + '"' + ',');
                        }

                    });
                    html.push('"state"' + ':' + '"true"' + '}');
                });
                html.push(']');
                var loadHtml = html.join("");
                // console.log(loadHtml);
                if (loadHtml.isJSON()) {
                    var dd = JSON.parse(loadHtml);
                    $("#tt").datagrid({
                        data: dd
                    });
                    //清除选中所有行
                    $("#tt").datagrid('clearSelections');
                }
            }
        });
    } else {
        $.messager.alert("操作提示", "只能选一个记录修改！", "info");
        return;
    }

}
/**
 * 新增
 */
function btnAddOrgRole() {
    setGlobalVariable("role", "");
    top.layer.open({
        type: 2,
        title: ['分配组织机构与角色','background: #38acff;'],
        shadeClose: false,
        shade: 0.3,
        area: ['710px', '500px'],
        content: path +'/system/user/orgRoleAllot' //iframe的url
        , end: function () {
            //需要需要对datagrid insertRows
            //同时需要判断 新增的值是不是操作原有的orgCode 是则更新updateRows 否则insertRows

            var setRolesData = getGlobalVariable("setOrgRoles");
            if (setRolesData.isJSON()) {
                setRolesDataArray = JSON.parse(setRolesData)[0];
                //map新增
                oldRolesByOrgMap.put(setRolesDataArray.orgCode, setRolesDataArray);
            } else {
                setRolesDataArray = [];
            }

            //先清空 datagrid中含有的数据
            $("#tt").datagrid("loadData", {total: 0, rows: []});
            //再添加datagrid数据
            //拼接rows内json
            var html = new Array();
            html.push('[');
            $.each(oldRolesByOrgMap.elements, function (i, v) {
                if (i == 0) {
                    html.push('{');
                } else {
                    html.push(',{');
                }
                $.each(v.value, function (index, val) {
                    if ("roleDtos" == index) {
                        html.push('"' + index + '" : ' + val + ',');
                    } else {
                        html.push('"' + index + '" : ' + '"' + val + '"' + ',');
                    }

                });
                html.push('"state"' + ':' + '"true"' + '}');
            });
            html.push(']');
            var loadHtml = html.join("");
            // console.log(loadHtml);
            if (loadHtml.isJSON()) {
                var dd = JSON.parse(loadHtml);
                $("#tt").datagrid({
                    data: dd
                });
                //清除选中所有行
                $("#tt").datagrid('clearSelections');
            }
        }
    });
}

/**
 * 删除
 */
function  btnDelNodeByGrid() {
    var rows = $('#tt').datagrid('getSelections');
    if (rows.length == 0) {
        $.messager.alert("操作提示", "请选一个记录！", "info");
        return;
    } else {
        $.messager.alert("操作提示", "是否要删除选中的权限分配?","confirm", function () {

                for (var i = 0; i < rows.length; i++) {
                    var orgCode = rows[i].orgCode;
                    oldRolesByOrgMap.remove(orgCode);
                }

                //先清空 datagrid中含有的数据
                $("#tt").datagrid("loadData", {total: 0, rows: []});
                //再添加datagrid数据
                //拼接rows内json
                var html = new Array();
                html.push('[');
                $.each(oldRolesByOrgMap.elements, function (i, v) {
                    if (i == 0) {
                        html.push('{');
                    } else {
                        html.push(',{');
                    }
                    $.each(v.value, function (index, val) {
                        if ("roleDtos" == index) {
                            html.push('"' + index + '" : ' + val + ',');
                        } else {
                            html.push('"' + index + '" : ' + '"' + val + '"' + ',');
                        }

                    });
                    html.push('"state"' + ':' + '"true"' + '}');
                });
                html.push(']');
                var loadHtml = html.join("");
                // console.log(loadHtml);
                if (loadHtml.isJSON()) {
                    var dd = JSON.parse(loadHtml);
                    $("#tt").datagrid({
                        data: dd
                    });
                    //清除选中所有行
                    $("#tt").datagrid('clearSelections');
                }
        });
    }

}